package zsc.liangyi.blog.web.Common;

import ch.qos.logback.core.util.FileUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zsc.liangyi.blog.model.ResponseData.ResponseData;
import zsc.liangyi.blog.model.ResponseData.StaticticsBo;
import zsc.liangyi.blog.model.domain.Article;
import zsc.liangyi.blog.model.domain.Comment;
import zsc.liangyi.blog.model.domain.User;
import zsc.liangyi.blog.service.ArticleService;
import zsc.liangyi.blog.service.CommentService;
import zsc.liangyi.blog.service.SiteService;
import zsc.liangyi.blog.service.UserService;
import zsc.liangyi.blog.utils.FileUtils;
import zsc.liangyi.blog.utils.UserUtils;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private SiteService siteService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    private final static int ARTICLE_MAX = 5;
    private final static int COMMENT_MAX = 5;

    //管理中心首页
    @GetMapping(value = {"", "/index"})
    public String index(Model model) {
        List<Article> articleList = siteService.recentArticles(ARTICLE_MAX);
        List<Comment> commentList = siteService.recentComments(COMMENT_MAX);
        StaticticsBo staticticsBo = siteService.getStatistics();
//        向model存储数据
        model.addAttribute("articles", articleList);
        model.addAttribute("comments", commentList);
        model.addAttribute("statistics", staticticsBo);
        return "back/index";
    }

    //跳转文章发布页面
    @GetMapping("/article/toEditPage")
    public String newArticle() {
        return "back/article_edit";
    }



    //跳转到后台文章列表页面
    @GetMapping("/article")
    public String index(@RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "count", defaultValue = "10") Integer count,
                        Model model) {
        PageInfo<Article> articlePageInfo = articleService.selectArticleWithPageByUserId(UserUtils.getUser().getId(), page, count);
        model.addAttribute("articles", articlePageInfo);
        return "back/article_list";
    }

    //跳转到收藏界面
    @GetMapping("/article/collect")
    public String collect(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "count", defaultValue = "10") Integer count,
                          Model model) {
        PageInfo<Article> articlePageInfo = articleService.selectArticleWithCollectByUserId(UserUtils.getUser().getId(), page, count);
        model.addAttribute("articles", articlePageInfo);
        return "back/article_collect";
    }
    //文章发布
    @PostMapping("/article/publish")
    @ResponseBody
    public ResponseData publishArticle(Article article) {
        article.setUserId(UserUtils.getUser().getId());
        try {
            articleService.publish(article);
            log.info("文章发布成功！" + article);
            return ResponseData.ok();
        } catch (Exception e) {
            log.error("文章发布失败:" + e.getMessage());
            return ResponseData.fail();
        }
    }
    //修改文章页面
    @GetMapping("/article/{id}")
    public String editArticle(@PathVariable("id") Integer id,
                              Model model) {
        Article article = articleService.selectArticleWithId(id);
        model.addAttribute("contents", article);
        return "back/article_edit";
    }

    //修改文章
    @PostMapping("/article/modify")
    @ResponseBody
    public ResponseData modifyArticle(Article article) {
        try {
            articleService.updateArticleWithId(article);
            log.info("文章更新成功");
            return ResponseData.ok();
        } catch (Exception e) {
            log.error("文章更新失败:" + e.getMessage());
            return ResponseData.fail();
        }
    }

    //删除文章
    @PostMapping("/article/delete")
    @ResponseBody
    public ResponseData deleteArticle(@RequestParam Integer id) {
        try {
            articleService.deleteArticleWithId(id);
            return ResponseData.ok();
        } catch (Exception e) {
            return ResponseData.fail();
        }
    }

    //个人中心管理界面
    @GetMapping("/myinfo")
    public String userinfo(Model model) {
        model.addAttribute("info", userService.getByUserName(UserUtils.getUser().getUsername()));
        return "back/myinfo";
    }

    //修改信息
    @GetMapping("/user/update")
    public String userUpdate(Model model) {
        model.addAttribute("info", userService.getByUserName(UserUtils.getUser().getUsername()));
        return "back/user_edit";
    }

    @PostMapping("/user/update")
    @ResponseBody
    public ResponseData userUpdate(@RequestParam(value = "file", required = false) MultipartFile file,
                                   @RequestParam(value = "email") String email,
                                   @RequestParam(value = "signature") String signature,
                                   @RequestParam(value = "password") String password,
                                   @RequestParam(value = "newpassword") String newpassword) {
        User user=new User();
        log.warn("传来的值：user:" + user + "|||" + file+"|||"+password);
        try {
            //修改头像
            if (file != null) {
                user.setAvatar(FileUtils.uploadAvatar(file));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        修改密码
        if(StringUtils.isNotBlank(password)||StringUtils.isNotBlank(newpassword)){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (!encoder.matches(password, UserUtils.getUser().getPassword())) {
                return ResponseData.fail("原密码错误");
            } else if (!password.equals(newpassword)) {
                return ResponseData.fail("新旧密码不一致");
            } else {
                user.setPassword(encoder.encode(password));
            }
        }

//        修改基本信息
        try {
            user.setId(UserUtils.getUser().getId());
            user.setEmail(email);
            user.setSignature(signature);
            userService.update(user);
            return ResponseData.success(user, 200);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.fail("修改信息失败");
        }
    }
}
